<?php

namespace App\Http\Controllers\Auth;

use App\Models\User;
use Dingo\Api\Exception\StoreResourceFailedException;
use Illuminate\Auth\Events\Registered;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array $data
     *
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:50',
            'username' => 'required|digits:11|unique:users',
            'password' => 'required|min:6',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array $data
     *
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'username' => $data['username'],
            'password' => bcrypt($data['password']),
        ]);
    }

    public function register(Request $request)
    {
        $rules = [
            'name' => 'required|max:50',
            'username' => 'required|digits:11|unique:users',
            'password' => 'required|min:6',
        ];

        $messages = [
            'name.required' => '请填写姓名',
            'username.required' => '请填写用户名',
            'password.required' => '请填写密码',
            'name.max' => '姓名不能超过50位',
            'username.digits' => '手机号码格式错误',
            'username.unique' => '该手机号码已经注册',
            'password.min' => '密码不能少于6位'
        ];

        $validator = Validator::make($request->all(), $rules, $messages);

        if ($validator->fails()) {
            throw new StoreResourceFailedException($validator->errors());
        }

        event(new Registered($user = $this->create($request->all())));

        $this->guard()->login($user);

        if ($this->registered($request, $user)) {
            throw new StoreResourceFailedException('register error');
        } else {
            return ['status_code' => 200];
        }
    }
}
